package com.common.util;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.crypt.dsig.*;
import org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet;
import org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet.SignatureConfigurable;

public class POIUtil {

    public static void main(String[] args) {
        String filePath = "path/to/excel/file.xlsx";
        String signerName = "Your Name";
        String privateKeyPath = "path/to/private/key.pfx";
        String password = "your_password";

        ExcelDigitalSignature signer = new ExcelDigitalSignature();
        signer.addDigitalSignature(filePath, signerName, privateKeyPath, password);
    }


    public void addDigitalSignature(String filePath, String signerName, String privateKeyPath, String password) {
        try {
            OPCPackage pkg = OPCPackage.open(filePath);
            SignatureConfigurable signatureConfigurable = (SignatureConfigurable) pkg.getDigitalSignatureConfig();
            signatureConfigurable.setSignatureFacet(SignatureFacet.class, privateKeyPath, password);

            SignatureInfo si = new SignatureInfo();

            si.setOpcPackage(pkg);
            si.setSignatureConfigurable(signatureConfigurable);
            si.confirmSignature();

            pkg.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
